<?php
namespace app\api\controller;
use app\common\controller\BaseApi;

/*进出记录api*/
class MysqlBackUp extends  BaseApi
{
	/**
	 * 测试地址
	 * http://zwzl.com/api/MysqlBackUp/back_up/
	 * */
	 public function _initialize()
    {
    }
	public function test(){
		db_dump();
	}
	/**
	 * 备份
	 * */
	public  function back_up(){
		$sqldir=config("database.sql_dir");
		if(empty($sqldir)){
			\Think\Log::write("未配置sql_dir","err");
			var_dump("未配置sql_dir");die;
		}else{
			$files=scandir($sqldir);
			$result='';	
			//进行备份处理
			foreach ($files as $key => $value) {
				if($this->str_starts_with($value,date("ymd"))){
					$result[]=$value;
				}else{//删除3天前的备份
					if(strlen($value)>6&&(substr($value, 0,6)<date("ymd",strtotime('-3 day')))){
						unlink($sqldir."/".$value);
					}
				}
			}			
			$asyn_url=config("database.asyn_url");
			var_dump($this->upload_file_to_cdn($asyn_url,$sqldir."/",config('database.shop_name'),config('database.shop_id')));
		}
	}


  function str_starts_with($haystack, $needle) {
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
  }

 

  function str_ends_with($haystack, $needle) {
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
  }
  
  public function upload_file_to_cdn($url,$furl,$shop_name,$shop_id){
  	//备份本地数据库
  	$file_name=db_dump();
	if($file_name==FALSE){
		return ;
	}
	$furl.=$file_name;
  	$client = new \GuzzleHttp\Client();
	$body = fopen($furl, 'r');
	$dir="./data/sql/".config("database.shop_name");
	$response=$client->request('POST',$url, [
		'multipart' => [
        [
            'name'     => 'files',
            'contents' => fopen($furl, 'r')
        ],
        [
            'name'     => 'dir_name',
            'contents' => $dir,
        ],
        [
        	'name'		=>'shop_name',
        	'contents' =>$shop_name        
        ],
        [	'name'=>'shop_id',
        	'contents'=>$shop_id
        ]
		
	]]);
	echo $response->getBody();
  }
////////////////////////////////////////////////////////////////////////////////////
}
